import axios from 'axios';
import { getAliyunConfig, validateAliyunConfig } from './aliyunConfig';
import type { AliyunConfig } from './aliyunConfig';
// 聊天消息接口
export interface ChatMessage {
  role: 'system' | 'user' | 'assistant';
  content: string;
}

// 聊天请求接口
export interface ChatRequest {
  model: string;
  input: {
    messages: ChatMessage[];
  };
  parameters?: {
    temperature?: number;
    top_p?: number;
    max_tokens?: number;
    stop?: string[];
  };
}

// 聊天响应接口
export interface ChatResponse {
  output: {
    text: string;
    finish_reason: string;
    usage: {
      total_tokens: number;
      input_tokens: number;
      output_tokens: number;
    };
  };
  request_id: string;
}

// 阿里云通义千问聊天服务类
export class AliyunChatService {
  private config: AliyunConfig;

  constructor(config?: Partial<AliyunConfig>) {
    this.config = { ...getAliyunConfig(), ...config };
    
    if (!validateAliyunConfig(this.config)) {
      throw new Error('阿里云配置不完整，请检查API Key等配置');
    }
  }

  /**
   * 发送聊天消息
   * @param messages 消息历史
   * @param parameters 可选参数
   * @returns Promise<string> 助手回复
   */
  async chat(
    messages: ChatMessage[], 
    parameters?: {
      temperature?: number;
      top_p?: number;
      max_tokens?: number;
      stop?: string[];
    }
  ): Promise<string> {
    try {
      const requestData: ChatRequest = {
        model: this.config.chatModel,
        input: {
          messages: messages
        },
        parameters: {
          temperature: 0.7,
          top_p: 0.8,
          max_tokens: 1500,
          ...parameters
        }
      };

      const response = await axios.post<ChatResponse>(
        `${this.config.baseUrl}/services/aigc/text-generation/generation`,
        requestData,
        {
          headers: {
            'Authorization': `Bearer ${this.config.apiKey}`,
            'Content-Type': 'application/json',
            'X-DashScope-SSE': 'disable'
          }
        }
      );

      return response.data.output.text;
    } catch (error) {
      console.error('聊天请求失败:', error);
      throw new Error(`聊天失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }

  /**
   * 智能客服回复（结合知识库）
   * @param userMessage 用户消息
   * @param knowledgeBase 知识库内容
   * @param systemPrompt 系统提示词
   * @returns Promise<string> 智能回复
   */
  async intelligentReply(
    userMessage: string,
    knowledgeBase: string[],
    systemPrompt: string = '你是一个专业的客服助手，请根据知识库内容回答用户问题。如果知识库中没有相关信息，请礼貌地说明无法提供相关信息。'
  ): Promise<string> {
    try {
      // 构建包含知识库的上下文
      const context = knowledgeBase.length > 0 
        ? `\n\n知识库信息：\n${knowledgeBase.join('\n')}`
        : '';

      const messages: ChatMessage[] = [
        {
          role: 'system',
          content: systemPrompt + context
        },
        {
          role: 'user',
          content: userMessage
        }
      ];

      return await this.chat(messages);
    } catch (error) {
      console.error('智能回复失败:', error);
      throw new Error(`智能回复失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }

  /**
   * 流式聊天（如果需要）
   * @param messages 消息历史
   * @param onChunk 处理每个数据块的函数
   * @param parameters 可选参数
   */
  async chatStream(
    messages: ChatMessage[],
    onChunk: (chunk: string) => void,
    parameters?: {
      temperature?: number;
      top_p?: number;
      max_tokens?: number;
      stop?: string[];
    }
  ): Promise<void> {
    try {
      const requestData: ChatRequest = {
        model: this.config.chatModel,
        input: {
          messages: messages
        },
        parameters: {
          temperature: 0.7,
          top_p: 0.8,
          max_tokens: 1500,
          ...parameters
        }
      };

      const response = await axios.post(
        `${this.config.baseUrl}/services/aigc/text-generation/generation`,
        requestData,
        {
          headers: {
            'Authorization': `Bearer ${this.config.apiKey}`,
            'Content-Type': 'application/json',
            'X-DashScope-SSE': 'enable'
          },
          responseType: 'stream'
        }
      );

      // 处理流式响应
      response.data.on('data', (chunk: Buffer) => {
        const text = chunk.toString();
        const lines = text.split('\n');
        
        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.slice(6);
            if (data === '[DONE]') {
              return;
            }
            try {
              const parsed = JSON.parse(data);
              if (parsed.output?.text) {
                onChunk(parsed.output.text);
              }
            } catch (e) {
              // 忽略解析错误
            }
          }
        }
      });
    } catch (error) {
      console.error('流式聊天失败:', error);
      throw new Error(`流式聊天失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }
}

// 创建默认的聊天服务实例
export const chatService = new AliyunChatService(); 